package com.mac.web;

import com.alibaba.fastjson.JSON;
import com.mac.pojo.PageBean;
import com.mac.pojo.User;
import com.mac.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    // 定义Logger对象
    private static final Logger LOGGER = LoggerFactory.getLogger("UserServlet.Class");

    private final UserService userService = new UserService();

    public void login(HttpServletRequest request,HttpServletResponse response) throws  ServletException,IOException {

        // 获取用户名
        String username = null;
        try {
            username = request.getParameter("username");
            LOGGER.info("request.getParameter(\"username\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"username\") -> failed",e);
            throw new RuntimeException(e);
        }

        // 获取用户输入的密码
        String password = null;
        try {
            password = request.getParameter("password");
            LOGGER.info("request.getParameter(\"password\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"password\") -> failed",e);
        }

        // 获取用户输入的验证码
        String userCaptcha = null;
        try {
            userCaptcha = request.getParameter("userCaptcha");
            LOGGER.info("request.getParameter(\"userCaptcha\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"userCaptcha\") -> failed",e);
            throw new RuntimeException(e);
        }

        String captcha = null;
        try {
            // 获取程序生成的验证码
            HttpSession session = request.getSession();
            captcha = (String) session.getAttribute("captcha");
            LOGGER.info("(String) session.getAttribute(\"captcha\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("(String) session.getAttribute(\"captcha\") -> failed",e);
            throw new RuntimeException(e);
        }

        if (username == null || password == null){
            response.getWriter().write("loginFailed");
        }else {
            if (userCaptcha == null || captcha == null){
                response.getWriter().write("captchaFailed");
            }else {
                User user = userService.checkUser(username, password);

                if (!userCaptcha.equalsIgnoreCase(captcha)) {
                    response.getWriter().write("captchaFailed");
                } else {
                    if (!userCaptcha.equalsIgnoreCase(captcha)) {
                        response.getWriter().write("captchaFailed");
                    } else {
                        if (user != null) {
                            HttpSession session = request.getSession();
                            session.setAttribute("user", user);
                            response.getWriter().write("success");
                        } else {
                            response.getWriter().write("loginFailed");
                        }
                    }
                }
            }
        }
    }

    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取用户名和密码
        String username = null;
        try {
            username = request.getParameter("username");
            LOGGER.info("request.getParameter(\"username\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"username\") -> failed",e);
            throw new RuntimeException(e);
        }

        String password = null;
        try {
            password = request.getParameter("password");
            LOGGER.info("request.getParameter(\"password\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"password\") -> failed",e);
        }

        String password2 = null;
        try {
            password2 = request.getParameter("password2");
            LOGGER.info("request.getParameter(\"password2\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"password2\") -> failed",e);
        }

        String userCaptcha = null;
        try {
            // 获取用户输入的验证码
            userCaptcha = request.getParameter("captcha");
            LOGGER.info("request.getParameter(\"checkCode\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"checkCode\") -> failed");
            throw new RuntimeException(e);
        }

        // 获取邮箱
        String email;
        try {
            email = request.getParameter("email");
            LOGGER.info("request.getParameter(\"email\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"email\") -> failed",e);
            throw new RuntimeException(e);
        }

        // 获取手机号
        String telephone = null;
        try {
            telephone = request.getParameter("telephone");
            LOGGER.info("request.getParameter(\"telephone\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"telephone\") -> failed",e);
            throw new RuntimeException(e);
        }


        if (username == null){
            response.getWriter().write("usernameIsEmpty");
            return;
        }else if (username.trim().isEmpty()){
            response.getWriter().write("usernameIsEmpty");
        }

        if (password == null){
            response.getWriter().write("passwordIsEmpty");
            return;
        }else if (password.trim().isEmpty()){
            response.getWriter().write("passwordIsEmpty");
        }

        if (password2 == null){
            response.getWriter().write("password2IsEmpty");
            return;
        }else if (password2.trim().isEmpty()){
            response.getWriter().write("password2IsEmpty");
        }

        if (email == null){
            response.getWriter().write("emailIsEmpty");
            return;
        }else if (email.trim().isEmpty()){
            response.getWriter().write("emailIsEmpty");
        }

        if (telephone == null){
            response.getWriter().write("telephoneIsEmpty");
            return;
        }else if (telephone.trim().isEmpty()){
            response.getWriter().write("telephoneIsEmpty");
        }

        if (userCaptcha == null){
            response.getWriter().write("userCaptchaIsEmpty");
            return;
        }else if (userCaptcha.trim().isEmpty()){
            response.getWriter().write("userCaptchaIsEmpty");
        }

        String checkCodeGen = null;
        try {
            // 获取程序生成的验证码
            HttpSession session = request.getSession();
            checkCodeGen = (String) session.getAttribute("captcha");
            LOGGER.info("(String) session.getAttribute(\"checkCodeGen\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("(String) session.getAttribute(\"checkCodeGen\") -> failed", e);
            throw new RuntimeException(e);
        }

        if (checkCodeGen == null || !checkCodeGen.equalsIgnoreCase(userCaptcha)) {
            // 发送响应：验证码错误
            response.getWriter().write("captchaWrong");
            return;
        }

        if (password.equals(password2)){
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);
            user.setTelephone(telephone);

            // 调用service注册
            boolean flag = userService.addUser(user);

            // 判断注册是否成功
            if (flag) {
                // 发送响应，用户注册成功
                response.getWriter().write("succeed");
            } else {
                // 发送响应：用户已经存在
                response.getWriter().write("userArExists");
            }
        }else {
            response.getWriter().write("passwordNotSame");
        }
    }
    public void  changePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String password = null;
        try {
            password = request.getParameter("password");
            LOGGER.info("request.getParameter(\"password\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"password\") -> failed",e);
        }

        String password2 = null;
        try {
            password2 = request.getParameter("password2");
            LOGGER.info("request.getParameter(\"password2\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"password2\") -> failed",e);
        }

        String userCaptcha = null;
        try {
            // 获取用户输入的验证码
            userCaptcha = request.getParameter("captcha");
            LOGGER.info("request.getParameter(\"checkCode\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"checkCode\") -> failed");
            throw new RuntimeException(e);
        }

        // 获取手机号
        String telephone = null;
        try {
            telephone = request.getParameter("telephone");
            LOGGER.info("request.getParameter(\"telephone\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"telephone\") -> failed",e);
            throw new RuntimeException(e);
        }
        System.out.println("userCaptcha: " + userCaptcha);
        System.out.println("telephone: " + telephone);
        System.out.println("password: " + password);
        System.out.println("password2: " + password2);

        if (password == null){
            response.getWriter().write("passwordIsEmpty");
            return;
        }else if (password.trim().isEmpty()){
            response.getWriter().write("passwordIsEmpty");
            return;
        }

        if (password2 == null){
            response.getWriter().write("password2IsEmpty");
            return;
        }else if (password2.trim().isEmpty()){
            response.getWriter().write("password2IsEmpty");
            return;
        }

        if (telephone == null){
            response.getWriter().write("telephoneIsEmpty");
            return;
        }else if (telephone.trim().isEmpty()){
            response.getWriter().write("telephoneIsEmpty");
            return;
        }


        if (userCaptcha == null){
            response.getWriter().write("userCaptchaIsEmpty");
            return;
        }else if (userCaptcha.trim().isEmpty()){
            response.getWriter().write("userCaptchaIsEmpty");
            return;
        }



        String checkCodeGen = null;
        try {
            // 获取程序生成的验证码
            HttpSession session = request.getSession();
            checkCodeGen = (String) session.getAttribute("captcha");
            LOGGER.info("(String) session.getAttribute(\"checkCodeGen\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("(String) session.getAttribute(\"checkCodeGen\") -> failed", e);
            throw new RuntimeException(e);
        }

        if (checkCodeGen == null || !checkCodeGen.equalsIgnoreCase(userCaptcha)) {
            // 发送响应：验证码错误
            response.getWriter().write("captchaWrong");
            return;
        }

        if(!password.equals(password2)){
            response.getWriter().write("passwordNotSame");
            return;
        }
        User user = userService.checkTelephone(telephone);
        if (user == null) {
            response.getWriter().write("userisNotFound");
        }else{
            User user_new = new User();
            user_new.setUserId(user.getUserId());
            user_new.setUsername(user.getUsername());
            user_new.setPassword(password);
            user_new.setEmail(user.getEmail());
            user_new.setTelephone(user.getTelephone());
            user_new.setGender(user.getGender());
            try {
                userService.changeUserInfo(user_new);
                LOGGER.info("userService.changeUserInfo(user_new) -> succeed");
            } catch (Exception e) {
                LOGGER.error("userService.changeUserInfo(user_new) -> failed", e);
                throw new RuntimeException(e);
            }
            response.getWriter().write("updateSucceed");
        }
    }
    public void  deleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession(true);
        User user = (User) session.getAttribute("user");
        if(user != null){
            if(userService.deleteUser(user.getUsername())){
                LOGGER.info("userService.deleteUser(username) -> succeed");
                if (session != null) {
                    session.invalidate();//这个方法属于HttpSession接口，用于使当前的会话无效，并解除与此会话相关联的所有对象。
                    LOGGER.info("session.invalidate() -> succeed");
                    response.getWriter().write("deleteUserSucceed");
                }else{
                    LOGGER.error("session.invalidate() -> failed");
                }
            }else{
                LOGGER.error("userService.deleteUserFail(username) -> failed");
                response.getWriter().write("deleteUserFail");
            }
        }else{
            LOGGER.error(" deleteUser() -> failed");
        }

    }

    public void loginOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        if (session != null) {
            session.invalidate();
            LOGGER.info("session.invalidate() -> succeed");
            response.getWriter().write("loginOutSucceed");
        }else {
            LOGGER.error("session.invalidate() -> failed");
            response.getWriter().write("loginOutFailed");
        }
    }


    public void changeUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String usernameNew = null;
        try {
            usernameNew = request.getParameter("username");
            LOGGER.info(" request.getParameter(\"username\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"username\") -> failed", e);
            response.getWriter().write("changeUserFail");
        }


       String telephoneNew = null;
        try {
            telephoneNew = request.getParameter("telephone");
            LOGGER.info(" request.getParameter(\"telephone\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"telephone\") -> failed", e);
            response.getWriter().write("changeUserFail");
        }


        String emailNew = null;
        try {
            emailNew = request.getParameter("email");
            LOGGER.info(" request.getParameter(\"email\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"email\") -> failed", e);
            response.getWriter().write("changeUserFail");
        }

        String userGenderNew=null;
        try {
            userGenderNew = request.getParameter("userGender");
            LOGGER.info(" request.getParameter(\"userGender\") -> succeed");
        } catch (Exception e) {
            LOGGER.error("request.getParameter(\"userGender\") -> failed", e);
            response.getWriter().write("changeUserFail");
        }

        User user=null;
        HttpSession session = request.getSession(true);
        if(session != null){
             user = (User) session.getAttribute("user");
        }

      if(userGenderNew.equals("1")){
          userGenderNew="男";
      }else{
          userGenderNew="女";
      }

        if(user!=null){
            User userNew;
            userNew = new User();
            userNew.setUserId(user.getUserId());
            userNew.setUsername(usernameNew);
            userNew.setEmail(emailNew);
            userNew.setTelephone(telephoneNew);
            userNew.setGender(userGenderNew);
            try {
                userService.changeUserInfo(userNew);
                LOGGER.info("userService.changeUserInfo(userNew) -> succeed");
                response.getWriter().write("changeSucceed");
            } catch (Exception e) {
                LOGGER.error("userService.changeUserInfo(userNew) -> failed", e);
                response.getWriter().write("changeUserFail");
            }

        }else{
            LOGGER.error("changeUser() -> failed");
            response.getWriter().write("changeUserFail");
        }




    }
    public void selectAllUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        ArrayList<User> users = null;
        try {
            users = userService.selectAll();
            LOGGER.info("userService.selectAll() -> success");
        } catch (Exception e) {
            LOGGER.error("userService.selectAll() -> failed",e);
            response.getWriter().write("failed");
        }

        // 转化为jsonString
        String jsonString = JSON.toJSONString(users);

        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }



    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1. 接收user数据
        BufferedReader br = request.getReader();
        String params = br.readLine();//json字符串

        //转为User对象
        User user = JSON.parseObject(params,User.class);

        //2. 调用service添加
        userService.addUser(user);

        //3. 响应成功的标识
        response.getWriter().write("success");
    }

    /**
     * 批量删除
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 接收数据
        BufferedReader br = request.getReader();
        String params = br.readLine();//json字符串

        //转为 int[]
        int[] ids = JSON.parseObject(params, int[].class);

        System.out.println(Arrays.toString(ids));

        for (int id : ids) {
            User user = userService.selectByUserId(id);

            if (user.getRole().equals("admin") || user.getRole().equals("members")){
                response.getWriter().write("failed");
                return;
            }else {
                // 调用service删除
                userService.deleteByIds(ids);
            }
        }
        // 响应成功
        response.getWriter().write("success");
    }

    /**
     * 分页查询
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收 当前页码 和 每页展示条数    url?currentPage=1&pageSize=5
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");

        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        // 调用service查询
        PageBean<User> pageBean = userService.selectByPage(currentPage, pageSize);

        // 转为JSON
        String jsonString = JSON.toJSONString(pageBean);
        // 写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }




    /**
     * 分页条件查询
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收 当前页码 和 每页展示条数    url?currentPage=1&pageSize=5
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");

        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        // 获取查询条件对象
        BufferedReader br = request.getReader();
        String params = br.readLine();//json字符串

        //转为 User 对象
        User user = JSON.parseObject(params, User.class);


        // 调用service查询
        PageBean<User> pageBean = userService.selectByPageAndCondition(currentPage,pageSize,user);

        // 转为JSON数据
        String jsonString = JSON.toJSONString(pageBean);
        // 响应数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }
}



